# -*- coding: utf-8 -*-
"""Controller module"""
__author__ = "Lei Chen <hide1713@gmail.com>"
import logging
import os

from file_reader.cog_file_reader import CogFileReader
from file_reader.genome_file_reader import TextFileReader
from file_reader.hitp_file_reader import HitpFileReader
import view.draw as draw

class MainWindowController(object):
    """
    Controller for main window
    """
    
    def __init__(self, model):
        """
        Arguments:
        - `model`: is a Model object
        """
        self.log = logging.getLogger(self.__class__.__name__)
        self._cog = None #The cog family map
        self._model = model
        
    def get_model(self):
        return self._model

    def load_cog_file(self, file_name):
        """Load cog from file
        
        Arguments:
        - `file_name`: file path
        """
        self.log.debug("Loading COG file:" + file_name)
        reader = CogFileReader()
        self._cog = reader.read(file_name)
        

    def load_data_file(self, file_name, user_id=None):
        """Load genome data file
        
        Arguments:
        - `file_name`: file path
        """
        reader = TextFileReader()
        new_model = reader.generate_model(file_name, self._cog)
        new_model.owner = user_id
        self._model.add_data(new_model)
        self.log.debug("Load data file:" + file_name)

    def remove_data_file(self, file_name,user_id):
        """Remove data file from model
        """
        self._model.remove_data(file_name,user_id)
        
    def load_data_directory(self, directory_name):
        """Load data files in directory_name
        """
        if os.path.isdir(directory_name):
            self.log.info("Loading Data Directory " + directory_name)
            for dirname, dirnames, filenames in os.walk(directory_name):
                if not dirname.endswith("family"):
                    continue
                for file_name in filenames: 
                    user_id = int(dirname.split("/")[-2])
                    file_name = os.path.join(dirname,file_name)
                    reader = TextFileReader()
                    new_model = reader.generate_model(file_name, self._cog)
                    new_model.owner = user_id
                    self._model.add_data(new_model)
        else:
            self.log.error("Can not find data directory:" + directory_name)
            
    def set_hitp_folder(self, path):
        """Set the hitp data folder
        
        Arguments:
        - `path`:
        """
        if os.path.isdir(path):
            self.hitp_folder = path
        else:
            raise Exception("%s is not a folder"%path)

    def get_cogs(self, cog_selection, user_id):
        """Return a list of cog object
        """
        cogs = []
        for cog_name, file_name in cog_selection:
            cog = self._model.get_cog(cog_name, file_name, user_id)
            cogs.append(cog)
        return cogs

    def get_cogs_with_hitp(self, cog_selection, user_id):
        """Return a list of cog object and hitp data
        cog_selection: is a list of (cog_name, file_name) from UI
        """
        cogs = []
        hitp_reader = HitpFileReader()
        for cog_name, file_name in cog_selection:
            self.log.debug("Loading draw data %s %s"%(cog_name, file_name))
            cog = self._model.get_cog(cog_name, file_name, user_id)
            hitp_path = self.hitp_folder + cog_name + ".cons"
            hitp_data = hitp_reader.read_hitp_values_from_file(hitp_path)
            cog.hitp = hitp_data
            cogs.append(cog)
        return cogs
    
    def draw_segment(self, cog_selection,user_id):
        """
        Draw segment recruitment
        Arguments:
        - `cog_selection`:(cog_name, file_name)
        - `user_id`: user id
        """
        self.log.info("Drawing segment recruitment")
        cogs = self.get_cogs(cog_selection,user_id)
        return draw.draw_segment_recruitment(cogs)    
        
    def draw_coverage(self, cog_selection,user_id):
        """Draw Coverage Frequency
        
        Arguments:
        - `cog_selection`: (cog, file_name)
        - `user_id`: user id
        """
        self.log.info("Drawing coverage frequency")
        cogs = self.get_cogs_with_hitp(cog_selection,user_id)
        return draw.draw_freq(cogs)

    def draw_function_category(self, cog_files, user_id):
        """Draw function category"""
        cog_models = []
        #Load selected child model
        for file_name in cog_files:
            cog_models.append(self._model.get_child_model(file_name,\
                                                          user_id))
        return draw.draw_function_category(cog_models)
        
    def draw_similarity_tree(self, cog_selection):
        """Draw the clustering of different communities (datasets) based on
        their functional similarity (spearman correlation of the relative abundance
        of different COG functions)"""
        cog_models = []
        #Load selected child model
        for cog_name, file_name in cog_selection:
            cog_models.append(self._model.get_child_model(file_name))
        draw.draw_similarity(cog_models)
        
        



